package cn.apestar.common.push;

import java.util.HashSet;
import cn.apestar.common.config.Global;
import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.device.TagAliasResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Message.Builder;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;

/**
 * 激光推送
 * 
 * @author lvh
 */
public class PushUtil {

	private static final String appKey = Global.getConfig("JG_appKey");
	private static final String masterSecret = Global
			.getConfig("JG_masterSecret");
	// 初始化激光推送
	public static JPushClient jpushClient = new JPushClient(masterSecret,
			appKey, 3);

	public String sendPush(String messageContent) {
		return "";
	}

	/**
	 * 发送给所有人
	 * 
	 * @param messageContent
	 *            内容
	 * @param title
	 *            标题
	 * @return
	 */
	public static PushPayload buildPushObjectAll(String messageContent,
			String title) {
		Builder m = Message.newBuilder();
		m.setContentType("text");
		m.setMsgContent(messageContent);
		m.setTitle(title);
		return PushPayload.newBuilder().setPlatform(Platform.all())
				.setAudience(Audience.all()).setMessage(m.build()).build();
	}

	/**
	 * 发送给某个人
	 * 
	 * @param messageContent
	 *            内容
	 * @param title
	 *            标题
	 * @return
	 */
	public static PushPayload buildPushObjectBySomeOne(String messageContent,
			String title) {
		Builder m = Message.newBuilder();
		m.setContentType("text");
		m.setMsgContent(messageContent);
		m.setTitle(title);
		return PushPayload.newBuilder().setPlatform(Platform.all())
				.setAudience(Audience.all()).setMessage(m.build()).build();
	}

	/**
	 * 增加设备 和别名
	 * 
	 * @param registration_id
	 *            设备ID
	 * @param tag
	 *            别名
	 * @return
	 */
	public static void addDeviceTag(String registrationId, String tag) {
		try {
			TagAliasResult result = jpushClient
					.getDeviceTagAlias(registrationId);
			if (result == null) {
				HashSet<String> h = new HashSet();
				h.add(tag);
				jpushClient.updateDeviceTagAlias(registrationId, null, h, null);
			}
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIRequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
